package com.neu.commons.Dao;

import com.neu.commons.Utils.dbutils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BaseDao {


    public int  BaseDaoUpdate(String sql,Object...obj){
        int row=0;
        QueryRunner qr=new QueryRunner(dbutils.getDataSource());
        try {
            row=qr.update(sql,obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }


    public List<Map<String, Object>> BaseDaoQuery(String sql, Object...obj){
        List<Map<String, Object>> list=new ArrayList<>();
        QueryRunner qr=new QueryRunner(dbutils.getDataSource());
        try {
            list=qr.query(sql,new MapListHandler(),obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }
    public Object BaseDaoBatchQuery(String sql, Object...obj){
       Object o="";
        QueryRunner qr=new QueryRunner(dbutils.getDataSource());
        try {

            o=qr.query(sql, new ScalarHandler<String>(),obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return o;
    }
    public int  BaseDaoAddbatch(String sql,List<List<String>>list){
        int row=0;
        Object[][]obj=new Object[list.size()][];
        for(int i=0;i<list.size();i++){
            List<String> item=list.get(i);
            System.out.println("item:"+item);
            obj[i]=new Object[item.size()];
            for (int j=0;j<item.size();j++){
                obj[i][j]=item.get(j);
            }
        }

        QueryRunner qr=new QueryRunner(dbutils.getDataSource());
        try {
            qr.batch(sql,obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        row=1;
        return row;
    }
}
